/**
 * @author
 * @createtime
 * @class ProjectFinalauditForm
 * @extends Ext.Window
 * @description ProjectFinalaudit表单
 */
ProjectFinalauditForm = Ext.extend(Ext.Window, {
	//内嵌FormPanel
	formPanel : null,
	//构造函数
	constructor : function(_cfg) {
		Ext.applyIf(this, _cfg);
		//必须先初始化组件
		this.initUIComponents();
		ProjectFinalauditForm.superclass.constructor.call(this, {
			id : 'ProjectFinalauditFormWin',
			layout : 'fit',
			items : this.formPanel,
			modal : true,
			width : 780,
			height : 430,
			maximizable : true,
			title : '[决算审计]详细信息',
			buttonAlign : 'center',
			buttons : this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents : function() {
		var thizId = this.id;
		this.formPanel = new Ext.FormPanel({
			layout : 'form',
			trackResetOnLoad : true,
			bodyStyle : 'padding:10px 10px 10px 10px',
			border : false,
			url : __ctxPath + '/project/saveProjectFinalaudit.do',
			id : 'ProjectFinalauditForm',
			defaults : {
				anchor : '98%,98%'
			},
			defaultType : 'textfield',
			items : [{
						name : 'projectFinalaudit.id',
						id : 'id',
						xtype : 'hidden',
						value : this.id == null ? '' : this.id
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '项目名称：',
									width : 100
								}, {
									xtype : 'textfield',
									name : 'projectFinalauditProName',
									id : 'projectFinalauditProName',
									columnWidth : .5,
									allowBlank : false,
									emptyText : '请选择项目',
									listeners : {
										'focus' : function() {
											ProjectSelector.getView(function(proId, proName, proNo) {
												Ext.getCmp("projectFinalaudit.project.id").setValue(proId);
												Ext.getCmp("projectFinalauditProName").setValue(proName);
											}, true).show();
										}
									}
								}, {
									xtype : "hidden",
									name : "projectFinalaudit.project.id",
									id : "projectFinalaudit.project.id"
								}, {
									text : '项目经理：',
									style : 'margin-left:10px;',
									width : 60
								}, {
									xtype : 'textfield',
									name : 'projectFinalauditManageUser',
									id : 'projectFinalauditManageUser',
									readOnly : true,
									emptyText : '请选择项目经理',
									columnWidth : .4,
									listeners : {
										focus : function() {
											UserSelector.getView(function(ids, names) {
												Ext.getCmp("projectFinalauditManageUser").setValue(names);
												Ext.getCmp("projectFinalaudit.manageUser.userId").setValue(ids);
											}, true).show();
										}
									}
								}, {
									xtype : "hidden",
									name : "projectFinalaudit.manageUser.userId",
									id : "projectFinalaudit.manageUser.userId"
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '预计总成本(元)：',
									width : 100
								}, {
									xtype : 'numberfield',
									name : 'projectFinalaudit.preTotal',
									id : 'preTotal',
									columnWidth : .3,
									allowBlank : false,
									maxLength : 9,
									regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
									regexText : '请输入正确格式的金额'
								}, {
									text : '材料成本(元)：',
									style : 'margin-left:10px;',
									width : 90
								}, {
									xtype : 'numberfield',
									name : 'projectFinalaudit.materialCost',
									id : 'materialCost',
									allowBlank : false,
									columnWidth : .3,
									maxLength : 9,
									regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
									regexText : '请输入正确格式的金额'
								}, {
									text : '比例(%)：',
									style : 'margin-left:10px;',
									width : 60
								}, {
									xtype : 'numberfield',
									name : 'projectFinalaudit.percentage',
									id : 'percentage',
									allowBlank : false,
									columnWidth : .3,
									maxLength : 9,
									regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
									regexText : '请输入正确格式的金额'
								}, {
									text : '%'
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '决算审计详情：'
								}, {
									style : 'color:red',
									id : 'projectFinalauditErrorLabel',
									text : '(*必填)'
								}]
					}, {
						xtype : 'container',
						style : 'padding-left:0px;margin-bottom:10px',
						layout : 'column',
						items : [{
									name : 'resultGridData',
									xtype : 'hidden',
									id : 'projectFinalaudit.resultGridData'
								}, {
									name : 'dataList',
									xtype : 'hidden',
									id : 'projectFinalaudit.dataList'
								}, {
									xtype : 'grid',
									id : 'projectFinalaudit.resultGridDataGrid',
									height : 220,
									width : '98%',
									stripeRows : true,
									trackMouseOver : true,
									clicksToEdit : 1,
									plugins : [new Ext.ux.grid.RowEditor({
										saveText : '保存',
										cancelText : '取消',
										errorText : '请输入完整信息',
										errorSummary : false
									})],
									store : new Ext.data.JsonStore({
										url : __ctxPath + '/project/listProjectFinalauditInfo.do',
										root : 'result',
										totalProperty : 'totalCounts',
										remoteSort : true,
										fields : ['id', 'shouldPayAmount', 'supplier', 'payedAmoumt', 'percentage', 'amount', 'insureAmount', 'remark'],
										listeners : {
											'update' : function(value) {
												var r = this.getRange();
												var resultArray = [];
												var jsonArr = [];
												var sum = 0;
												var rlen = r.length;
												for (var i = 0; i < rlen; i++) {
													resultArray.push([]);
													if (r[i].fields) {
														var fields = r[i].fields;
														var flen = fields.length;
														var obj = {
															id : null,
															shouldPayAmount : '',
															supplier : '',
															payedAmoumt : '',
															percentage : '',
															amount : '',
															insureAmount : '',
															remark : ''
														}
														for (var z = 0; z < flen; z++) {
															var fieldValue = r[i].get(fields.keys[z]);
															if (Ext.isEmpty(fieldValue) || fieldValue == '请双击选择' || fieldValue == '请双击填写') {
																continue;
															}
															if (fields.keys[z] == 'id') {
																if (fieldValue != '') {
																	obj.id = fieldValue;
																}
															} else if (fields.keys[z] == 'shouldPayAmount') {
																resultArray[i].push('应付款:' + fieldValue);
																obj.shouldPayAmount = fieldValue;
															} else if (fields.keys[z] == 'supplier') {
																resultArray[i].push('供应商:' + fieldValue);
																obj.supplier = fieldValue;
															} else if (fields.keys[z] == 'payedAmoumt') {
																resultArray[i].push('已付金额:' + fieldValue);
																obj.payedAmoumt = fieldValue;
															} else if (fields.keys[z] == 'percentage') {
																resultArray[i].push('比例:' + fieldValue);
																obj.percentage = fieldValue;
															} else if (fields.keys[z] == 'amount') {
																resultArray[i].push('金额:' + fieldValue);
																obj.amount = fieldValue;
															} else if (fields.keys[z] == 'insureAmount') {
																resultArray[i].push('其中保证金:' + fieldValue);
																obj.insureAmount = fieldValue;
															} else if (fields.keys[z] == 'remark') {
																resultArray[i].push('备注:' + fieldValue + ";");
																obj.remark = fieldValue;
															}
														}
														jsonArr.push(obj);
													}
												}
												//删除空元素
												for (var i = 0; i < resultArray.length; i++) {
													if (resultArray[i].length == 0) {
														resultArray.splice(i, 1);
														i--;
													}
												}
												Ext.getCmp('projectFinalaudit.resultGridData').setValue(resultArray);
												Ext.getCmp('projectFinalaudit.dataList').setValue(Ext.util.JSON.encode(jsonArr));
											}
										}
									}),
									cm : new Ext.grid.ColumnModel({
										columns : [new Ext.grid.RowNumberer(), {
													dataIndex : 'id',
													width : 50,
													hidden : true
												}, {
													header : '应付款(元)',
													dataIndex : 'shouldPayAmount',
													width : 120,
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'projectFinalauditInfo.shouldPayAmount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '供应商',
													dataIndex : 'supplier',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'projectFinalauditInfo.supplier',
														allowBlank : false,
														maxLength : 64
													}))
												}, {
													header : '已付金额(元)',
													dataIndex : 'payedAmoumt',
													width : 120,
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'projectFinalauditInfo.payedAmoumt',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '比例(%)',
													dataIndex : 'percentage',
													width : 120,
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'projectFinalauditInfo.percentage',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '金额(元)',
													dataIndex : 'amount',
													width : 120,
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'projectFinalauditInfo.amount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '其中保证金(元)',
													dataIndex : 'insureAmount',
													width : 120,
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'projectFinalauditInfo.insureAmount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
													header : '备注',
													dataIndex : 'remark',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														id : 'projectFinalauditInfo.remark'
													})),
													width : 150
												}],
										defaults : {
											sortable : false,
											menuDisabled : false,
											width : 100
										}
									}),
									tbar : new Ext.Toolbar({
										height : 30,
										items : [{
													iconCls : 'btn-add',
													text : '添加',
													xtype : 'button',
													handler : function() {
														var DataRecord = Ext.data.Record.create([{
																	name : 'id'
																}, {
																	name : 'shouldPayAmount'
																}, {
																	name : 'supplier'
																}, {
																	name : 'payedAmoumt'
																}, {
																	name : 'percentage'
																}, {
																	name : 'amount'
																}, {
																	name : 'insureAmount'
																}, {
																	name : 'remark'
																}]);
														var store = Ext.getCmp('projectFinalaudit.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectFinalaudit.resultGridDataGrid');

														var n1 = '';
														var n2 = 0;

														var newRowData = {
															shouldPayAmount : n1,
															supplier : n1,
															payedAmoumt : n1,
															percentage : n1,
															amount : n1,
															insureAmount : n1,
															remark : n1
														};
														var newRecord = new DataRecord(newRowData);
														store.add([newRecord]);

														grid.getSelectionModel().on('selectionchange', function(sm) {
															Ext.getCmp('projectFinalaudit.removeBtn').setDisabled(sm.getCount() < 1);
														});
													}
												}, {
													iconCls : 'btn-del',
													text : '删除',
													id : 'projectFinalaudit.removeBtn',
													xtype : 'button',
													handler : function() {
														var store = Ext.getCmp('projectFinalaudit.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectFinalaudit.resultGridDataGrid');
														var s = grid.getSelectionModel().getSelections();
														for (var i = 0, r; r = s[i]; i++) {
															store.remove(r);
														}
														store.fireEvent("update");//更新事件
													}
												}]
									})
								}]
					}, {
						xtype : 'textfield',
						hidden : true,
						validator : function() {
							var resultGridData = Ext.getCmp('projectFinalaudit.resultGridData').getValue();
							var errorLabel = Ext.getCmp("projectFinalauditErrorLabel");
							if (Ext.isEmpty(thizId)) {
								if (Ext.isEmpty(resultGridData)) {//为空显示提示
									errorLabel.setText('请填写决算审计详情');
									return false;
								}
							}
							return true
						}
					}]
		});
		//加载表单对应的数据	
		this.initData();
		//初始化功能按钮
		this.buttons = [{
					text : '保存',
					iconCls : 'btn-save',
					handler : this.save.createCallback(this.formPanel, this)
				}, {
					text : '重置',
					iconCls : 'btn-reset',
					handler : this.reset.createCallback(this.formPanel)
				}, {
					text : '取消',
					iconCls : 'btn-cancel',
					handler : this.cancel.createCallback(this)
				}];
	},//end of the initcomponents
	/**
	 * 初始化数据
	 * 
	 * @param {}
	 *            formPanel
	 */
	initData : function() {
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('projectFinalaudit.resultGridDataGrid').getStore().load({params:{
					'Q_finalAudit.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/project/getProjectFinalaudit.do?id=' + this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if (!Ext.isEmpty(res.project)) {
						Ext.getCmp("projectFinalauditProName").setValue(res.project.proName);
						Ext.getCmp("projectFinalauditProName").originalValue = res.project.proName;
						Ext.getCmp("projectFinalaudit.project.id").setValue(res.project.id);
						Ext.getCmp("projectFinalaudit.project.id").originalValue = res.project.id;
					}
					if (!Ext.isEmpty(res.manageUser)) {
						Ext.getCmp("projectFinalauditManageUser").setValue(res.manageUser.fullname);
						Ext.getCmp("projectFinalauditManageUser").originalValue = res.manageUser.fullname;
						Ext.getCmp("projectFinalaudit.manageUser.userId").setValue(res.manageUser.userId);
						Ext.getCmp("projectFinalaudit.manageUser.userId").originalValue = res.manageUser.userId;
					}
					//Ext.getCmp("").originalValue=
				},
				failure : function(form, action) {
				}
			});
		}
	},
	/**
	 * 重置
	 * 
	 * @param {}
	 *            formPanel
	 */
	reset : function(formPanel) {
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * 
	 * @param {}
	 *            window
	 */
	cancel : function(window) {
		window.close();
	},
	/**
	 * 保存记录
	 */
	save : function(formPanel, window) {
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel = Ext.getCmp('ProjectFinalauditGrid');
					if (gridPanel != null) {
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.ERROR
					});
					//window.close();
				}
			});
		}
	}//end of save

});